<template>
    <div class="checkbox-group">
        <slot></slot>
    </div>
</template>
<script>
import emitter from '@/mixins/emitter.js'
import { findComponentsDownward } from '../../assets/js/findComponent.js'
export default {
  name: 'dj-checkbox-group',
  mixins: [emitter],
  props: {
    value: {
      type: Array,
      required: true
    }
  },
  data () {
    return {
      currentValue: this.value,
      checkboxList: []
    }
  },
  watch: {
    value (newVal) {
      this.currentValue = newVal
      this.updateModel()
    },
    currentValue (newVal) {
      this.$emit('input', newVal)
      this.$emit('change', newVal)
    }
  },
  methods: {
    change (val, isAdd) {
      if (isAdd) {
        this.currentValue.push(val)
      } else {
        let index = this.currentValue.indexOf(val)
        this.currentValue.splice(index, 1)
      }
      this.dispatch('dj-form-item', 'form-change', this.currentValue)
    },
    updateModel () {
      this.checkboxList = findComponentsDownward(this, 'dj-checkbox')
      if (this.checkboxList) {
        this.checkboxList.forEach(item => {
          if (this.value.includes(item.label)) {
            item.isChecked = true
          } else {
            item.isChecked = false
          }
        })
      }
    }
  }

}
</script>
<style lang="scss" scoped>

</style>
